//
//  Menu.m
//  Maze1
//
//  Created by Lin Tian on 10/7/11.
//  Copyright 2011 tina. All rights reserved.
//

#import "Menu.h"


@implementation Menu

-(id)init
{
    if ((self = [super initWithColor:ccc4(255, 255, 255, 100)])) {
        
        CCSprite *menuItem=[CCSprite spriteWithFile:@"Icon-Small.png"];
        menuItem.position = ccp(200,200);
        [self addChild:menuItem z:2 tag:LOGOUT];
        
        menuItem=[CCSprite spriteWithFile:@"Icon-Small.png"];
        menuItem.position = ccp(300,200);
        [self addChild:menuItem z:2 tag:BACKTOGAME];
        
        menuItem=[CCSprite spriteWithFile:@"Icon-Small.png"];
        menuItem.position = ccp(400,200);
        [self addChild:menuItem z:2 tag:LEAVEGAME];
        
        [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:kCCMenuTouchPriority-1 swallowsTouches:YES];
    }
    return self;
}

-(void)dealloc
{
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super dealloc];
}

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    return YES;
}

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint touchLocation = [touch locationInView:[touch view]];
    touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
    touchLocation = [self convertToNodeSpace:touchLocation];
    
    if (ccpDistance(touchLocation, [self getChildByTag:LOGOUT].position) < [self getChildByTag:LOGOUT].contentSize.height/2) {
        [self logout];
    }else if(ccpDistance(touchLocation, [self getChildByTag:BACKTOGAME].position) < [self getChildByTag:BACKTOGAME].contentSize.height/2)
    {
        [self backToGame];
    }else if(ccpDistance(touchLocation, [self getChildByTag:LEAVEGAME].position) < [self getChildByTag:LEAVEGAME].contentSize.height/2)
    {
        [self leaveGame];
    }
}

-(void)logout
{
    [PackageParser sharedPackageParser].state = PlayerStateLoggingOut;
}

-(void)backToGame
{
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [(CCLayer*)self.parent removeChild:self cleanup:YES];
}

-(void)leaveGame
{
    [PackageParser sharedPackageParser].state = PlayerStateLeavingRoom;
}
@end
